<?php
class NewsController extends CommonController {
	public function index() {
		$condition = "category_id=".intval($_GET['category_id']);
		if (isset ( $_GET ['title'] ) && trim ( $_GET ['title'] ) != '') {
			$condition .= " and title like '%" . filter_trim ( $_GET ['title'] ) . "%'";
		}
		$count = M ( $this->table )->where ( $condition )->count ();
		$p = new Page ( $count );
		$list = M ( $this->table )->field ( 'id,title,category_id,create_time,update_time,is_home' )->where ( $condition )->order ( 'id desc' )->limit ( $p->firstRow . ',' . $p->listRows )->select ();
		$this->assign ( 'list', $list );
		$this->assign('page',$p->show());
		$this->display ();
	}
	public function save() {
		if ($this->isGet ()) {
			$this->display ( $this->tpl );
		} else {
			$db = D ( $this->table );
			$db->create () or $this->error ( $db->getError () );
			if ($db->save ( $_POST )) {
				$this->redirect ( 'index?category_id='.$_POST['category_id'] );
			} else {
				$this->error ($db->getError()?$db->getError():'添加失败');
			}
		}
	}
	public function update() {
		if ($this->isGet ()) {
			if ($this->useModel) {
				$info = D ( $this->table )->where ( 'id=' . intval ( $_GET ['id'] ) )->find ();
			} else {
				$info = M ( $this->table )->where ( 'id=' . intval ( $_GET ['id'] ) )->find ();
			}
			$this->assign ( 'info', $info );
			if ($this->tpl == null)
				$this->display ( 'save' );
			else
				$this->display ( $this->tpl );
		} else {
			$db = D ( $this->table );
			$db->create () or $this->error ( $db->getError () );
			if ($db->update ( $_POST )) {
				$this->redirect ( 'index?category_id='.$_POST['category_id']);
			} else {
				$this->error ($db->getError()?$db->getError():'编辑失败' );
			}
		}
	}
	public function saveBefore(){
		$category_list=M('NewsCategory')->order('sort asc')->select();
		$this->assign('category_list',$category_list);
	}
	public function updateBefore(){
		$category_list=M('NewsCategory')->order('sort asc')->select();
		$this->assign('category_list',$category_list);
	}
}